import { Col, Layout, Input } from 'antd'
import { useContext ,useState} from 'react'
import { AppContext } from '@/store'
import { useNavigate, useLocation } from 'react-router-dom'
import Logo from '../../assets/logo.png'
import exampleIcon from "../../assets/example_icon.png"
import SendArea from '../../components/SendArea'
import { CreateNewChat,GetExampleAPI} from '@/apis'
import './index.less'
import { useEffect } from 'react'

const { Content } = Layout
const { TextArea } = Input

const Home = () => {
  const { state, dispatch } = useContext(AppContext)
  const [examples, setExamples] = useState([])
  const location = useLocation()

  const navigate = useNavigate()
  const sendHandle = async (keyword) => {
    // 判断登录
    if (!state.token) {
      dispatch({ type: 'SET_VISIBLE', payload: true })
      return
    }
    const chat = await CreateNewChat()
    if (chat.success) {
      const message = {
        type: 'user',
        content: keyword,
      }
      dispatch({ type: 'SET_MESSAGE_LIST', payload: [message] })
      navigate(`/chat`)
    }else if(chat.code === 401){
      localStorage.removeItem("token")
      localStorage.removeItem("user")
      dispatch({ type: 'SET_VISIBLE', payload: true })
    }
  }

  const getExamples = async() =>{
    const result = await GetExampleAPI()
    if(result.success){
      setExamples(result.data)
      console.log("result:",result.data)
    }
  }

  useEffect(() => {
    const currentPath = location.pathname
    dispatch({ type: 'SET_PATHNAME', payload: currentPath })
    getExamples()
  }, [])
  return (
    <Layout className="layout-container">
      <Col span={24} className="header-logo">
        <img src={Logo} alt="logo" />
      </Col>
      <Content className="home-content">
        <SendArea sendHandle={sendHandle} />
        <Col className='examples'>
          <Col className='example-title'> <img src={exampleIcon} alt="" /> 试试这些超长文本的例子～</Col>
          <Col className='example-list'>
            {
              examples.map((item,index) =>(
                <Col key={index} className='example-item btn' onClick={()=>sendHandle(item.content)}>{item.content}</Col>
              ))
            }
          </Col>
        </Col>
      </Content>
    </Layout>
  )
}

export default Home
